from Tkinter import *
import Tkinter
import tkMessageBox

import jarvars
from save import saveConfiguration
class editCodes(Frame):

    def __init__(self, master=None):
        
        
        codes = jarvars.AuthorizedCodes        
            
            

        self.win = Toplevel(master)
        self.win.geometry("%dx%d%+d%+d" % (400, 100, 150, 0))
        Frame.__init__(self,self.win)
        self.code = StringVar()

        self.grid(padx=2, pady=2,sticky=N+S+E+W)


        self.codeLabel = Label(self, text="Code")
        self.codeToAdd = Entry(self, width=15)
        self.codeToAddLabel = Label(self, text="Code to add")
        self.addButton = Button(self, text="Add", command=self.addCode)
        self.removeButton = Button(self, text="Remove Selected", command=self.removeCode)
        if len(codes) > 0:
            self.codes = OptionMenu(self, self.code, *codes)
            self.code.set(jarvars.AuthorizedCodes[0])
        else:
            self.codes = Label(self, text="No Current Codes")

        self.codeLabel.grid(row=0, column=0, sticky=E)
        self.codes.grid(row=0,column=1, sticky=W)
        self.removeButton.grid(row=0, column=2, sticky=W)
        self.codeToAddLabel.grid(row=1, column=0, sticky = E)
        self.codeToAdd.grid(row=1, column=1, sticky=W)
        self.addButton.grid(row=1,column=2, sticky=W)
        self.bind("<Destroy>", self._destroy)
        self.master.title("Edit Codes")
        
       
    def addCode(self):
        
        code = self.codeToAdd.get()
        if len(code) == 0:
            return
        print "Add Code", code
        jarvars.AuthorizedCodes.append(code)
        if len(jarvars.AuthorizedCodes) == 1:
            print "Switch stuff"
            self.codes.grid_forget()
            self.codes = OptionMenu(self, self.code, *jarvars.AuthorizedCodes)        
            self.codes.grid(row=0,column=1, sticky=W)
            self.code.set(code)
        else:
            menu = self.codes["menu"]
            menu.insert('end', 'command', label=code, command=Tkinter._setit(self.code, code, None))
        self.codeToAdd.delete(0,END)
        

    def removeCode(self):
        code = self.code.get()
        print "Remove Code", code
        jarvars.AuthorizedCodes.remove(code)
        if len(jarvars.AuthorizedCodes)== 0:
            self.codes.grid_forget()
            self.codes = Label(self, text="No Codes")
            self.codes.grid(row=0, column=1, sticky=W)
        else:
            self.code.set(jarvars.AuthorizedCodes[0])
        menu = self.codes["menu"]
        menu.delete(code)


                
    def _destroy(self, Event=None):
        saveConfiguration()
        self.win.destroy()
    
if __name__ == "__main__":
    print "Not a main module"
    root = Tk()
    eu = editCodes(root)
    while(1):
        eu.update()
    
    


